<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/7/3
 * Time: 14:38
 */

namespace app\common\service\environmentAnalysis;

use app\common\service\CommonService;
use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;
use think\facade\Config;
use think\Db;

class EnvironmentAnalysisWeatherService
{
    public function getReduceBeforeContribution($param = [])
    {
        $pollutant_name = $param['is_sulfur'] ? 'SO2' : 'NO2';
        $commonService  = new CommonService();
        $param          = $commonService->getMongoTime($param);
        $companyIdArr   = $commonService->getCompanyIdArr(0);
        $list           = [];
        #贡献度趋势
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'concentration'       => 1, //该站点这一天的浓度和
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'contribution_name' => $pollutant_name,
                        'industry_id'       => (int)$param['industry_id'],
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'predict_time'      => [
                            '$gte' => $param['start_time'],
                            '$lte' => $param['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'               => '$publish_time',
                        'total'             => ['$sum' => '$contribution_degree'], //因为同一区域同一站点同一行业同一污染物同一天(不同企业)的数据存在多条,此处贡献值为每天的多个公司的和 20190619算法
                        'concentration_sum' => ['$avg' => '$concentration'], //mongodb表此字段已经是浓度和，因此此处求平均值即为这一天的该污染物的浓度和
                    ]
                ],
                [
                    '$sort' => [
                        '_id' => 1,
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $commonService      = new CommonService();
        $date_all           = $commonService->getDate($param['start_time'], $param['end_time']);
        $num                = count($contribution_trend[0]['result']);
        if ($num > 0) {
            for ($i = 0; $i < $num; $i++) {
                $list['date'][$i] = date('Y-m-d', strtotime($contribution_trend[0]['result'][$i]['_id']));
                $list['data'][0][$i] = $contribution_trend[0]['result'][$i]['concentration_sum'] > 0 ? $commonService->contributionRound($contribution_trend[0]['result'][$i]['total'] / $contribution_trend[0]['result'][$i]['concentration_sum']) : '';
            }
            # 比较差集
            $different     = array_values(array_diff($date_all, $list['date']));
            $different_num = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $list['date'][]    = $different[$i];
                    $list['data'][0][] = '';
                }
            }
        } else {
            $list['date'] = $date_all;
            for ($i = 0; $i < count($list['date']); $i++) {
                $list['data'][0][$i] = '';
            }
        }
        # 依据publish_time排序
        array_multisort($list['date'], $list['data'][0]);
        for ($m = 0; $m < count($list['date']); $m++) {
            $list['date'][$m]    = date('m/d', strtotime($list['date'][$m]));
//            $list['data'][0][$m] = $list['data'][0][$m] === '' ? '' : $list['data'][0][$m] * 100; //返给前端直接是百分比
            $list['data'][0][$m] = $list['data'][0][$m] === '' ? '' : $list['data'][0][$m]; //返给前端直接是百分比
            $list['data'][1][$m] = '-'; //减排后
        }
        return $list;
    }
}